<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>鼠标画多边形</title>
  <style>
    #canvas {
      border: 1px solid #000;
    }
  </style>
</head>
<body>

<canvas id="canvas" width="400" height="300"></canvas>

<script>
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');

  var points = [];
  var closeDistance = 10;  // 定义吸附距离
  var scaleFactor = 1;  // 初始缩放因子

  // 加载图片
  var image = new Image();
  image.src = 'path/to/your/image.jpg';  // 替换为您的图片路径
  image.onload = function() {
    ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
  };

  // 监听滚轮事件，实现缩放
  canvas.addEventListener('wheel', function(e) {
    e.preventDefault();
    var delta = e.deltaY || e.detail || e.wheelDelta;
    scaleFactor += delta > 0 ? -0.1 : 0.1;
    scaleFactor = Math.max(0.1, Math.min(scaleFactor, 3)); // 控制缩放范围

    redrawCanvas();
  });

  canvas.addEventListener('click', function(e) {
    var rect = canvas.getBoundingClientRect();
    var x = (e.clientX - rect.left) / scaleFactor;
    var y = (e.clientY - rect.top) / scaleFactor;

    // 如果是最后一个点，并且有一点与第一个点相同，结束绘制
    if (points.length > 1 && isCloseToFirstPoint(x, y)) {
      drawLines(points[points.length - 1].x, points[points.length - 1].y, points[0].x, points[0].y);
      points = [];  // 清空点数组
    } else {
      points.push({ x, y });
      drawPoint(x, y);

      if (points.length > 1) {
        var prevPoint = points[points.length - 2];
        drawLines(prevPoint.x, prevPoint.y, x, y);
      }
    }
  });

  function isCloseToFirstPoint(x, y) {
    // 判断当前点是否接近第一个点
    var firstPoint = points[0];
    var distance = Math.sqrt(Math.pow(x - firstPoint.x, 2) + Math.pow(y - firstPoint.y, 2));
    return distance < closeDistance;
  }

  function drawPoint(x, y) {
    ctx.beginPath();
    ctx.arc(x * scaleFactor, y * scaleFactor, 3, 0, 2 * Math.PI);
    ctx.fillStyle = 'red';
    ctx.fill();
  }

  function drawLines(x1, y1, x2, y2) {
    // 绘制线段
    ctx.beginPath();
    ctx.moveTo(x1 * scaleFactor, y1 * scaleFactor);
    ctx.lineTo(x2 * scaleFactor, y2 * scaleFactor);
    ctx.stroke();
  }

  function redrawCanvas() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(image, 0, 0, canvas.width * scaleFactor, canvas.height * scaleFactor);

    // 重新绘制多边形
    for (var i = 1; i < points.length; i++) {
      drawLines(points[i-1].x, points[i-1].y, points[i].x, points[i].y);
      drawPoint(points[i].x, points[i].y);
    }

    // 如果有足够的点，连接第一个点和最后一个点
    if (points.length > 1 && isCloseToFirstPoint(points[points.length-1].x, points[points.length-1].y)) {
      drawLines(points[points.length-1].x, points[points.length-1].y, points[0].x, points[0].y);
    }
  }
</script>

</body>
</html>
